package com.cms.web.business;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.biz.FlowManagerServiceMgr;
import com.cms.persistence.contractManager.accreditationContract.PSHTMX;
import com.cms.pub.CMSFlowPermission;
import com.common.util.DateUtil;
import com.metadata.biz.MetaDataServiceMgr;
import com.metadata.bizmodel.SYS_MODEL;
import com.persistence.FLOW_TASK_LIST;
import com.persistence.qxgl.beans.SYSUser;
import com.pub.util.EMPJsonUtil;
import com.web.BaseController;

import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.builder.meta.bizmodel.SYS_MDL_CTN;
import com.efounder.dict.DMTServiceMgr;
import com.efounder.dict.FCTServiceMgr;
import com.efounder.eai.data.JParamObject;
import com.efounder.form.EFFormDataModel;
import com.efounder.form.server.provider.FormModelDataProvider;
import com.efounder.form.server.resolver.util.FormModelDataResolverUtil;
import com.efounder.form.server.resolver.util.SYS_MDL_VAL;

/** 
 * 评审合同控制器
 * 
 * @author ES
 * @version 1.0
 */
@Controller
@RequestMapping(value="/contractManagerApproval")
public class AccreditationContractApprovalController extends BaseController{
	@Autowired
	private                            DMTServiceMgr                                   DMTService;
	
	@Autowired
	private                            FCTServiceMgr                                   FCTService;
	
	@Autowired
	private                       MetaDataServiceMgr                           metaDataServiceMgr;
	
	@Autowired
	private                    FlowManagerServiceMgr                           FlowManagerService;
	
	@Autowired
	private                FormModelDataResolverUtil                            formModelResolver;
	
	@Autowired
	private                    FormModelDataProvider                                formModelUtil;
	
	@Autowired
	public                               HttpSession                                      session;

	/**
	 * 评审合同列表
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/accreditationContractApproval")
	public String accreditationContractList(Model model) throws Exception {	
		SYSUser                 user = (SYSUser) session.getAttribute("contextUser");
		EFDataSet          ndDataset = DMTService.searchDictRow("HTKJND", "F_NDBH", "", "1", 0, 100);
		Calendar                 cal = Calendar.getInstance();
		int                     year = cal.get(Calendar.YEAR);
		JParamObject              PO = JParamObject.Create();
		JParamObject          flowPO = JParamObject.Create();
		EFDataSet         flowNodeDS = null;
		EFDataSet           columnDS = EFDataSet.getInstance();
		EFRowSet        columnRowset = EFRowSet.getInstance();
		EFRowSet      flowNodeRowset = EFRowSet.getInstance();
		String            BILL_WHERE = " and RESR_IN_CAUSE != 'waiting' ";
		
		//获取流程节点
		flowPO.SetValueByParamName("TABLE_NAME", "FLOW_NODE_LIST");
		flowPO.SetValueByParamName("FLOW_ID", "PSHT_FLOW");
		flowPO.SetValueByParamName("FLOW_BM", user.getUSER_ORGID());
		flowPO.SetValueByParamName("FLOW_USER", user.getUSER_ID());
		flowPO.SetValueByParamName("BILL_ORDER", " NODE_ID");
		
		flowNodeDS = FlowManagerService.loadFlowNode(flowPO);
		
		//帮助列信息
		columnRowset = EFRowSet.getInstance();
		columnRowset.putString("COLUMN_BH", "BIZ_DJBH");
		columnRowset.putString("COLUMN_MC", "合同编号");
		columnDS.insertRowSet(columnRowset);
		columnRowset = EFRowSet.getInstance();
		columnRowset.putString("COLUMN_BH", "F_KHMC");
		columnRowset.putString("COLUMN_MC", "客户名称");
		columnDS.insertRowSet(columnRowset);
		columnRowset = EFRowSet.getInstance();
		columnRowset.putString("COLUMN_BH", "F_XMMC");
		columnRowset.putString("COLUMN_MC", "项目名称");
		columnDS.insertRowSet(columnRowset);
		
		model.addAttribute("flowNodeDS", flowNodeDS);
		model.addAttribute("columnDS", columnDS);
		model.addAttribute("ndDataset", ndDataset);
		model.addAttribute("F_KJND", year);
		
		if(flowNodeDS.getRowCount() > 0) {
			flowNodeRowset = flowNodeDS.getRowSet(0);
			PO.SetValueByParamName("TABLE_NAME", "FLOW_TASK_LIST");
			PO.SetValueByParamName("FLOW_ID", "PSHT_FLOW");
			PO.SetValueByParamName("FLOW_BM", user.getUSER_ORGID());
			PO.SetValueByParamName("FLOW_USER", user.getUSER_ID());
			PO.SetValueByParamName("TASK_TO_UNIT", user.getUSER_ORGID());
			PO.SetValueByParamName("TASK_TO_USER", user.getUSER_ID());
			PO.SetValueByParamName("FLOW_TAG", flowNodeRowset.getString("NODE_ID", ""));
			PO.SetValueByParamName("BILL_ORDER", " FLOW_TASK_LIST.NODE_TAG, FLOW_TASK_LIST.BIZ_DJBH desc");
			PO.SetValueByParamName("RESR_STATUS", "pending");
			
			BILL_WHERE += " and NODE_TAG = '" + flowNodeRowset.getString("NODE_ID", "") + "'";
			PO.SetValueByParamName("BILL_WHERE", BILL_WHERE);
			
			flowNodeDS = FlowManagerService.loadFlow(PO);
			model.addAttribute("dataset", flowNodeDS);
		}
		return "/cms/business/accreditationContractApproval/list";
	}
	
	/**
	 * 评审合同列表
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/accreditationContractApproval/list")
	public String accreditationContractList(@RequestParam String F_KJND, @RequestParam String FLOW_NODE, Model model) throws Exception {	
		SYSUser              user = (SYSUser) session.getAttribute("contextUser");
		EFDataSet       ndDataset = DMTService.searchDictRow("HTKJND", "F_NDBH", "", "1", 0, 100);
		EFDataSet      flowNodeDS = null;
		JParamObject           PO = JParamObject.Create();
		String         BILL_WHERE = "";
		EFDataSet          flowDS = null;
	
		flowNodeDS = getFlowNodeDataSet(user);
		
		BILL_WHERE = " and BIZ_DATE = '" + F_KJND + "' and ((NODE_TAG = '" + FLOW_NODE + "' and RESR_STATUS = 'pending') or "
		           + "(NODE_SRC = '" + FLOW_NODE + "' and RESR_STATUS = 'pending' and RESR_IN_CAUSE != 'rollback')) ";
		
		PO.SetValueByParamName("TABLE_NAME", "FLOW_TASK_LIST");
		PO.SetValueByParamName("FLOW_ID", "PSHT_FLOW");
		PO.SetValueByParamName("FLOW_BM", user.getUSER_ORGID());
		PO.SetValueByParamName("FLOW_USER", user.getUSER_ID());
		PO.SetValueByParamName("TASK_TO_UNIT", user.getUSER_ORGID());
		PO.SetValueByParamName("TASK_TO_USER", user.getUSER_ID());
		PO.SetValueByParamName("BILL_ORDER", " FLOW_TASK_LIST.NODE_TAG");
		PO.SetValueByParamName("BILL_WHERE", BILL_WHERE);
		
		flowDS = FlowManagerService.loadFlow1(PO);			
		model.addAttribute("dataset", flowDS);
		model.addAttribute("FLOW_NODE", FLOW_NODE);
		model.addAttribute("ndDataset", ndDataset);
		model.addAttribute("flowNodeDS", flowNodeDS);
		model.addAttribute("dataset", flowDS);
		model.addAttribute("F_KJND", F_KJND);
		return "/cms/business/accreditationContractApproval/list";
	}
	
	/**
	 * 获取会计期间
	 * @param F_YEAR
	 * @return
	 */
	private EFDataSet getFlowNodeDataSet(SYSUser user) {
		JParamObject          flowPO = JParamObject.Create();
		EFDataSet         flowNodeDS = null;
		
		//获取流程节点
		flowPO.SetValueByParamName("TABLE_NAME", "FLOW_NODE_LIST");
		flowPO.SetValueByParamName("FLOW_ID", "PSHT_FLOW");
		flowPO.SetValueByParamName("FLOW_BM", user.getUSER_ORGID());
		flowPO.SetValueByParamName("FLOW_USER", user.getUSER_ID());
		flowPO.SetValueByParamName("BILL_ORDER", " NODE_ID");
		
		flowNodeDS = FlowManagerService.loadFlowNode(flowPO);
		return flowNodeDS;
	}
	
	/**
	 * 评审合同添加保存
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/accreditationContractApproval/update", method=RequestMethod.POST)
	public  ModelAndView accreditationContractApprovalUpdate(@RequestBody Map dataMap, Model model) throws Exception {  
		EFRowSet              rowSet = EMPJsonUtil.convertMapToRowSet(dataMap);
		EFDataSet        itemDataSet = rowSet.getDataSet(PSHTMX.class.getName());
		EFRowSet              rowset = EFRowSet.getInstance();
		String              F_CHDATE = "";
		JParamObject              PO = JParamObject.Create();
		JParamObject          flowPO = JParamObject.Create();
		EFDataSet         flowNodeDS = null;
		EFRowSet          nodeRowset = EFRowSet.getInstance();
		SYSUser                 user = (SYSUser) session.getAttribute("contextUser");
		String            BILL_WHERE = " OP_ID = '" + dataMap.get("OP_ID") + "'";
		String            strEndDate = "";
		String                F_QSRQ = "";
		String                F_JZRQ = "";
		String               XG_JZRQ = "";
		int               betweenDay = 0;
		String               curDate = "";
		
		PO.SetValueByParamName("tableName", "FLOW_TASK_LIST");
		PO.SetValueByParamName("BILL_WHERE", BILL_WHERE);
		EFRowSet          flowRowSet = FCTService.getFCTRow(PO);
		
		PO.SetValueByParamName(SYS_MODEL.MODEL_ID, "PSHTModel");
		PO.SetValueByParamName(SYS_MODEL.SERVICE_ID, "FormProvider");
		PO.SetValueByParamName("BILL_WHERE", " F_GUID = '" + flowRowSet.getString("BIZ_GUID", "") + "'");
		
		//获取流程节点
		flowPO.SetValueByParamName("TABLE_NAME", "FLOW_NODE_LIST");
		flowPO.SetValueByParamName("FLOW_ID", "PSHT_EDIT_FLOW");
		flowPO.SetValueByParamName("FLOW_BM", user.getUSER_ORGID());
		flowPO.SetValueByParamName("FLOW_USER", user.getUSER_ID());
		flowPO.SetValueByParamName("NODE_ID", flowRowSet.getString("NODE_TAG", ""));
		flowPO.SetValueByParamName("BILL_ORDER", " NODE_ID");
		
		flowNodeDS = FlowManagerService.loadFlowNode(flowPO);
		nodeRowset = flowNodeDS.getRowSet(0);

		if(nodeRowset == null) {
			return ajaxDoneError("提交失败！原因：<br>【" + user.getUSER_ID() + "-" + user.getUSER_NAME() + "】没有权限提交单据！");
		}
		
		//N2节点是部门审批节点，需要跟新状态，其他节点不需要计算完成天数
		if(nodeRowset.getString("NODE_ID", "N2").equals("N2")) {
			curDate = DateUtil.date3String("yyyyMMdd");
			//更新分录状态
			for(int i = 0; i < itemDataSet.getRowCount(); i++) {
				itemDataSet.getRowSet(i).putString("F_FLZT", "0");
				F_QSRQ = itemDataSet.getRowSet(i).getString("F_QSRQ", "");
				F_JZRQ = itemDataSet.getRowSet(i).getString("F_JZRQ", "");
				XG_JZRQ = itemDataSet.getRowSet(i).getString("XG_JZRQ", "");
				if(F_QSRQ.trim().length() > 0 && XG_JZRQ.trim().length() > 0) {
					//计算完成天数
					betweenDay = DateUtil.daysBetween(F_QSRQ, "", XG_JZRQ, "");
					itemDataSet.getRowSet(i).putNumber("XG_WCTS", betweenDay);
				}
				//计算完成天数
				betweenDay = DateUtil.daysBetween(F_QSRQ, "", F_JZRQ, "");
				itemDataSet.getRowSet(i).putNumber("F_WCTS", betweenDay);
				
				strEndDate = (XG_JZRQ.equals("") ? F_JZRQ.replaceAll("-", "") : XG_JZRQ.replaceAll("-", ""));
				if(strEndDate.compareTo(curDate) >= 0) {
					itemDataSet.getRowSet(i).putString("F_QRZT", "1");
				} else {
					itemDataSet.getRowSet(i).putString("F_QRZT", "2");
				}
				
			}
		}
		
		itemDataSet.setTableName("PSHTMX");
		rowset.setDataMap(rowSet.getDataMap());
		rowset.remove(PSHTMX.class.getName());
		rowset.setDataSet("PSHTMX", itemDataSet);
		//N2节点是部门审批节点，需要跟新状态，其他节点不需要计算完成天数
		if(nodeRowset.getString("NODE_ID", "N2").equals("N2")) {
			rowset.putString(EFFormDataModel._FORMEDITSAVETYPE_, "" + EFFormDataModel._FORM_SAVE_ITEM_);
		} else {
			rowset.putString(EFFormDataModel._FORMEDITSAVETYPE_, "" + EFFormDataModel._FORM_SAVE_ITEMS_ALL_);
		}

		PO.SetValueByParamName(SYS_MODEL.SERVICE_ID, "SaveApprovalPSHTRToFlowResolver");
		PO.SetValueByParamName(SYS_MODEL.MODEL_ID, "PSHTModel");
		
		EFFormDataModel formDataModel = formModelResolver.saveForm("PSHTXX", rowset, PO);
		if(formDataModel.getFormSaveStatus() == EFFormDataModel._FORM_SAVE_FAIL_) {
			return ajaxDoneError("保存失败！原因：<br>" + formDataModel.getFormSaveMessage());
		}
		rowset = formDataModel.getBillDataSet().getRowSet(0);
		F_CHDATE = rowset.getObject("F_CHDATE", "").toString();
		model.addAttribute("F_CHDATE", F_CHDATE);
		model.addAttribute("F_DJBH", rowset.getObject("F_DJBH", ""));
		return ajaxDoneSuccess("单据保存成功！单据编号【" + rowset.getObject("F_DJBH", "") + "】"); 
	}
	
	/**
	 * 评审合同添加保存
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/accreditationContractApproval/submit", method=RequestMethod.POST)
	public  ModelAndView accreditationContractApprovalSubmit(@RequestBody Map dataMap, Model model) throws Exception {  
		EFRowSet              rowSet = EMPJsonUtil.convertMapToRowSet(dataMap);
		EFDataSet        itemDataSet = rowSet.getDataSet(PSHTMX.class.getName());
		EFRowSet              rowset = EFRowSet.getInstance();
		String              F_CHDATE = "";
		String               strDate = DateUtil.date3String(DateUtil.PATTERN_DATE);
		JParamObject              PO = JParamObject.Create();
		JParamObject          flowPO = JParamObject.Create();
		EFDataSet         flowNodeDS = null;
		EFRowSet          nodeRowset = EFRowSet.getInstance();
		SYSUser                 user = (SYSUser) session.getAttribute("contextUser");
		String            BILL_WHERE = " OP_ID = '" + rowSet.getString("OP_ID", "") + "'";

		PO.SetValueByParamName("tableName", "FLOW_TASK_LIST");
		PO.SetValueByParamName("BILL_WHERE", BILL_WHERE);
		EFRowSet          flowRowSet = FCTService.getFCTRow(PO);
		
		PO.SetValueByParamName(SYS_MODEL.MODEL_ID, "PSHTModel");
		PO.SetValueByParamName(SYS_MODEL.SERVICE_ID, "FormProvider");
		PO.SetValueByParamName("BILL_WHERE", " F_GUID = '" + flowRowSet.getString("BIZ_GUID", "") + "'");
		
		//获取流程节点
		flowPO.SetValueByParamName("TABLE_NAME", "FLOW_NODE_LIST");
		flowPO.SetValueByParamName("FLOW_ID", "PSHT_EDIT_FLOW");
		flowPO.SetValueByParamName("FLOW_BM", user.getUSER_ORGID());
		flowPO.SetValueByParamName("FLOW_USER", user.getUSER_ID());
		flowPO.SetValueByParamName("NODE_ID", flowRowSet.getString("NODE_TAG", ""));
		flowPO.SetValueByParamName("BILL_ORDER", " NODE_ID");
		
		flowNodeDS = FlowManagerService.loadFlowNode(flowPO);
		nodeRowset = flowNodeDS.getRowSet(0);

		if(nodeRowset == null) {
			return ajaxDoneError("提交失败！原因：<br>【" + user.getUSER_ID() + "-" + user.getUSER_NAME() + "】没有权限提交单据！");
		}
		
		for(int i = 0; itemDataSet != null && i < itemDataSet.getRowCount(); i++) {			
			PO.SetValueByParamName(FLOW_TASK_LIST._F_CHAR + "05", itemDataSet.getRowSet(i).getString("F_NOTE", ""));
			PO.SetValueByParamName(FLOW_TASK_LIST._F_DATE + "01", itemDataSet.getRowSet(i).getString("F_QSRQ", ""));
			PO.SetValueByParamName(FLOW_TASK_LIST._F_DATE + "02", itemDataSet.getRowSet(i).getString("F_JZRQ", ""));
			PO.SetValueByParamName(FLOW_TASK_LIST._F_NUM + "01", String.valueOf(itemDataSet.getRowSet(i).getNumber("F_WCTS", Integer.parseInt("0"))));
			
			PO.SetValueByParamName(FLOW_TASK_LIST._F_CHAR + "06", itemDataSet.getRowSet(i).getString("XG_NOTE", ""));
			PO.SetValueByParamName(FLOW_TASK_LIST._F_DATE + "03", itemDataSet.getRowSet(i).getString("XG_JZRQ", null));
			PO.SetValueByParamName(FLOW_TASK_LIST._F_NUM + "02", String.valueOf(itemDataSet.getRowSet(i).getNumber("XG_WCTS", Integer.parseInt("0"))));			
		}
		
		//更新分录状态
		if(!nodeRowset.getString("NODE_TYPE", "").equals("end")) {
			for(int i = 0; itemDataSet != null && i < itemDataSet.getRowCount(); i++) {
				itemDataSet.getRowSet(i).putString("F_FLZT", "1");				
			}
		}
		itemDataSet.setTableName("PSHTMX");
		rowset.setDataMap(rowSet.getDataMap());
		rowset.remove(PSHTMX.class.getName());
		rowset.setDataSet("PSHTMX", itemDataSet);
		rowset.putString("F_ZDRQ", strDate);
		rowset.putString(EFFormDataModel._FORMEDITSAVETYPE_, "" + EFFormDataModel._FORM_SAVE_ITEM_);
		
		if(nodeRowset.getString("NODE_NEXT", "N4").equals("N4")) {
			PO.SetValueByParamName(SYS_MODEL.SERVICE_ID, "CMSPSHTFormManagerToDepartmentConfirm");
		} else if(nodeRowset.getString("NODE_TYPE", "").equals("end")) {
			PO.SetValueByParamName(SYS_MODEL.SERVICE_ID, "CMSPSHTFormToDepartmentConfirm");
		}else {
			PO.SetValueByParamName(SYS_MODEL.SERVICE_ID, "SubmitApprovalPSHTRToFlowResolver");
		}

		PO.SetValueByParamName(SYS_MODEL.MODEL_ID, "PSHTModel");
		
		PO.SetValueByParamName(FLOW_TASK_LIST._OP_ID, flowRowSet.getString("OP_ID", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._FLOW_ID, "PSHT_EDIT_FLOW");
		PO.SetValueByParamName(FLOW_TASK_LIST._OP_NOTE, rowSet.getString("OP_NOTE", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._OP_NODE, nodeRowset.getString("NODE_ID", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._OP_NODE_TYPE, nodeRowset.getString("NODE_TYPE", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._NODE_SRC, nodeRowset.getString("NODE_ID", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._NODE_SRC_NAME, nodeRowset.getString("NODE_NAME", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._OP_BMBH, user.getUSER_ORGID());
		PO.SetValueByParamName(FLOW_TASK_LIST._OP_USER, user.getUSER_ID());
		PO.SetValueByParamName(FLOW_TASK_LIST._OP_USER_NAME, user.getUSER_NAME());
		PO.SetValueByParamName(FLOW_TASK_LIST._RESR_STATUS, "pending");
		PO.SetValueByParamName(FLOW_TASK_LIST._RESR_IN_CAUSE, "waiting");
		PO.SetValueByParamName(FLOW_TASK_LIST._RESR_OUT_CAUSE, "submit");
		PO.SetValueByParamName(FLOW_TASK_LIST._F_CHAR + "01", rowset.getString("F_KHBH", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._F_CHAR + "02", rowset.getString("F_KHMC", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._F_CHAR + "03", rowset.getString("F_XMBH", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._F_CHAR + "04", rowset.getString("F_XMMC", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._F_CHAR + "05", rowset.getString("F_BZ", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._F_CHAR + "06", rowset.getString("F_FSCS", ""));
		
		EFFormDataModel formDataModel = formModelResolver.saveForm("PSHTXX", rowset, PO);
		if(formDataModel.getFormSaveStatus() == EFFormDataModel._FORM_SAVE_FAIL_) {
			return ajaxDoneError("单据提交失败！原因：<br>" + formDataModel.getFormSaveMessage());
		}
		rowset = formDataModel.getBillDataSet().getRowSet(0);
		F_CHDATE = rowset.getObject("F_CHDATE", "").toString();
		model.addAttribute("F_CHDATE", F_CHDATE);
		model.addAttribute("F_DJBH", rowset.getObject("F_DJBH", ""));
		model.addAttribute("OP_ID", PO.GetValueByParamName("OP_ID", ""));
		return ajaxDoneSuccess("单据提交成功！"); 
	}
	
	/**
	 * 取回评审合同
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/accreditationContractApproval/retake", method=RequestMethod.POST)
	public  ModelAndView accreditationContractApprovalRetake(@RequestBody Map dataMap, Model model) throws Exception {  
		EFRowSet              rowSet = EMPJsonUtil.convertMapToRowSet(dataMap);
		EFDataSet        itemDataSet = rowSet.getDataSet(PSHTMX.class.getName());
		EFRowSet              rowset = EFRowSet.getInstance();
		String              F_CHDATE = "";
		JParamObject              PO = JParamObject.Create();
		JParamObject          flowPO = JParamObject.Create();
		EFDataSet         flowNodeDS = null;
		EFRowSet          nodeRowset = EFRowSet.getInstance();
		SYSUser                 user = (SYSUser) session.getAttribute("contextUser");
		String            BILL_WHERE = " POP_ID = '" + rowSet.getString("OP_ID", "") + "'";

		PO.SetValueByParamName("tableName", "FLOW_TASK_LIST");
		PO.SetValueByParamName("BILL_WHERE", BILL_WHERE);
		EFRowSet          flowRowSet = FCTService.getFCTRow(PO);
		
		PO.SetValueByParamName(SYS_MODEL.MODEL_ID, "PSHTModel");
		PO.SetValueByParamName(SYS_MODEL.SERVICE_ID, "FormProvider");
		PO.SetValueByParamName("BILL_WHERE", " F_GUID = '" + flowRowSet.getString("BIZ_GUID", "") + "'");
		
		//获取流程节点
		flowPO.SetValueByParamName("TABLE_NAME", "FLOW_NODE_LIST");
		flowPO.SetValueByParamName("FLOW_ID", "PSHT_EDIT_FLOW");
		flowPO.SetValueByParamName("FLOW_BM", user.getUSER_ORGID());
		flowPO.SetValueByParamName("FLOW_USER", user.getUSER_ID());
		flowPO.SetValueByParamName("NODE_ID", flowRowSet.getString("NODE_SRC", ""));
		flowPO.SetValueByParamName("BILL_ORDER", " NODE_ID");
		
		flowNodeDS = FlowManagerService.loadFlowNode(flowPO);
		nodeRowset = flowNodeDS.getRowSet(0);

		if(nodeRowset == null) {
			return ajaxDoneError("提交失败！原因：<br>【" + user.getUSER_ID() + "-" + user.getUSER_NAME() + "】没有权限提交单据！");
		}
		
		//更新分录状态
		if(!nodeRowset.getString("NODE_TYPE", "").equals("end")) {
			for(int i = 0; itemDataSet != null && i < itemDataSet.getRowCount(); i++) {
				itemDataSet.getRowSet(i).putString("F_FLZT", "0");
			}
		}
		itemDataSet.setTableName("PSHTMX");
		rowset.setDataMap(rowSet.getDataMap());
		rowset.remove(PSHTMX.class.getName());
		rowset.setDataSet("PSHTMX", itemDataSet);
		rowset.putString(EFFormDataModel._FORMEDITSAVETYPE_, "" + EFFormDataModel._FORM_SAVE_ITEM_);
		
		PO.SetValueByParamName(SYS_MODEL.SERVICE_ID, "RetakeApprovalPSHTRToFlowResolver");
		PO.SetValueByParamName(SYS_MODEL.MODEL_ID, "PSHTModel");
		
		PO.SetValueByParamName(FLOW_TASK_LIST._OP_ID, flowRowSet.getString("OP_ID", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._FLOW_ID, "PSHT_EDIT_FLOW");
		PO.SetValueByParamName(FLOW_TASK_LIST._OP_NODE, nodeRowset.getString("NODE_ID", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._OP_NODE_TYPE, nodeRowset.getString("NODE_TYPE", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._NODE_SRC, nodeRowset.getString("NODE_ID", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._NODE_SRC_NAME, nodeRowset.getString("NODE_NAME", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._NODE_TAG, nodeRowset.getString("NODE_ID", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._NODE_TAG_NAME, nodeRowset.getString("NODE_NAME", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._OP_BMBH, user.getUSER_ORGID());
		PO.SetValueByParamName(FLOW_TASK_LIST._OP_USER, user.getUSER_ID());
		PO.SetValueByParamName(FLOW_TASK_LIST._OP_USER_NAME, user.getUSER_NAME());
		PO.SetValueByParamName(FLOW_TASK_LIST._TASK_TO_UNIT, user.getUSER_ORGID());
		PO.SetValueByParamName(FLOW_TASK_LIST._RESR_STATUS, "pending");
		PO.SetValueByParamName(FLOW_TASK_LIST._RESR_STATUS, "pending");
		PO.SetValueByParamName(FLOW_TASK_LIST._RESR_IN_CAUSE, "retake");
		PO.SetValueByParamName(FLOW_TASK_LIST._RESR_OUT_CAUSE, "retake");
		PO.SetValueByParamName(FLOW_TASK_LIST._F_CHAR + "01", rowset.getString("F_KHBH", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._F_CHAR + "02", rowset.getString("F_KHMC", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._F_CHAR + "03", rowset.getString("F_XMBH", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._F_CHAR + "04", rowset.getString("F_XMMC", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._F_CHAR + "05", rowset.getString("F_BZ", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._F_CHAR + "06", rowset.getString("F_FSCS", ""));
		
		EFFormDataModel formDataModel = formModelResolver.saveForm("PSHTXX", rowset, PO);
		if(formDataModel.getFormSaveStatus() == EFFormDataModel._FORM_SAVE_ITEMS_ALL_) {
			return ajaxDoneError("单据取回失败！原因：<br>" + formDataModel.getFormSaveMessage());
		}
		rowset = formDataModel.getBillDataSet().getRowSet(0);
		F_CHDATE = rowset.getObject("F_CHDATE", "").toString();
		model.addAttribute("F_CHDATE", F_CHDATE);
		model.addAttribute("F_DJBH", rowset.getObject("F_DJBH", ""));
		model.addAttribute("OP_ID", PO.GetValueByParamName("OP_ID", ""));
		return ajaxDoneSuccess("单据取回成功！"); 
	}
	
	/**
	 * 评审合同编辑
	 * @param model
	 * @return
	 */
	@RequestMapping("/accreditationContractApproval/edit/{OP_ID}")
	public String accreditationContractApprovalEdit(@PathVariable("OP_ID") String OP_ID, Model model) {
		JParamObject           PO = JParamObject.Create();
		JParamObject       flowPO = JParamObject.Create();
		EFFormDataModel formModel;
		EFDataSet      flowNodeDS = null;
		EFRowSet       nodeRowset = EFRowSet.getInstance();
		EFRowSet       itemRowset = null;
		boolean           bRetake = false;
		SYSUser              user = (SYSUser) session.getAttribute("contextUser");
		String         BILL_WHERE = " OP_ID = '" + OP_ID + "'";
		String            endDate = "";
		Date                 date = null;
		Date                 jzrq = null;
		Date               xgJzrq = null;
		Date                 qrrq = null;
		
		//检索当前的代办任务
		PO.SetValueByParamName("tableName", "FLOW_TASK_LIST");
		PO.SetValueByParamName("BILL_WHERE", BILL_WHERE);
		EFRowSet       flowRowSet = FCTService.getFCTRow(PO);
		
		//如果任务已经结束，则需要检索已完成的任务
		PO.SetValueByParamName("tableName", "FLOW_TASK_END_LIST");
		PO.SetValueByParamName("BILL_WHERE", BILL_WHERE);
		EFRowSet    endFlowRowSet = FCTService.getFCTRow(PO);
		
		//检索代办任务的下一条任务
		PO.SetValueByParamName("tableName", "FLOW_TASK_LIST");
		PO.SetValueByParamName("BILL_WHERE", " POP_ID = '" + OP_ID + "'");
		EFRowSet   nextFlowRowSet = FCTService.getFCTRow(PO);
		//检索有经理审批后部门退回的任务
		Map<String, EFRowSet> retakeMap = new HashMap<String, EFRowSet>();
		//检索已经结束流程的任务
		Map<String, EFRowSet> endFlowMap = new HashMap<String, EFRowSet>();
		//检索已经结束流程的任务
		Map<String, EFRowSet> departmentConfrimeFlowMap = new HashMap<String, EFRowSet>();
		
		String                  curDate = DateUtil.date3String(DateUtil.PATTERN_DATE);
		
		PO.SetValueByParamName(SYS_MODEL.MODEL_ID, "PSHTModel");
		PO.SetValueByParamName(SYS_MODEL.SERVICE_ID, "FormProvider");
		if(flowRowSet == null) {
			BILL_WHERE = " ####.F_GUID = '" + endFlowRowSet.getString("BIZ_GUID", "") + "'";
		} else {
			BILL_WHERE = " ####.F_GUID = '" + flowRowSet.getString("BIZ_GUID", "") + "'";
		}
		PO.SetValueByParamName("BILL_WHERE", BILL_WHERE);
		
		//获取流程节点
		flowPO.SetValueByParamName("TABLE_NAME", "FLOW_NODE_LIST");
		flowPO.SetValueByParamName("FLOW_ID", "PSHT_EDIT_FLOW");
		flowPO.SetValueByParamName("FLOW_BM", user.getUSER_ORGID());
		flowPO.SetValueByParamName("FLOW_USER", user.getUSER_ID());
		if(flowRowSet == null) {
			flowPO.SetValueByParamName("NODE_ID", "");
		} else {
			flowPO.SetValueByParamName("NODE_ID", flowRowSet.getString("NODE_TAG", ""));
		}
		
		flowPO.SetValueByParamName("BILL_ORDER", " NODE_ID");
		
		flowNodeDS = FlowManagerService.loadFlowNode(flowPO);
		nodeRowset = flowNodeDS.getRowSet(0);
		
		try {
			formModel = formModelUtil.loadForm(PO);
			EFDataSet itemCTN = metaDataServiceMgr.getSYS_MDL_CTN("PSHTModel", SYS_MDL_CTN._BIZ_CTN_TYPE_JIDS_);
			EFRowSet rowset = formModel.getBillDataSet().getRowSet(0);
			EFDataSet dataset = rowset.getDataSet(itemCTN.getRowSet(0).getString("CTN_FCT1", ""));

			String                            F_KJQJ = rowset.getString("F_KJND", "");
			String                            F_GUID = rowset.getString("F_GUID", "");
			String                            F_DJBH = rowset.getString("F_DJBH", null);
			BILL_WHERE = " BIZ_DJBH = '" + F_DJBH + "' and BIZ_DATE = '" + F_KJQJ + "' and BIZ_GUID = '" + F_GUID + "' and FLOW_ID = 'PSHT_EDIT_FLOW' and "
	                   + " NODE_SRC = 'N4' and NODE_TAG = 'N2' and RESR_IN_CAUSE = 'retake'";
			retakeMap = queryTask(PO, BILL_WHERE);
			
			BILL_WHERE = " BIZ_DJBH = '" + F_DJBH + "' and BIZ_DATE = '" + F_KJQJ + "' and BIZ_GUID = '" + F_GUID + "' and FLOW_ID = 'PSHT_EDIT_FLOW' and "
	                   + " TASK_STATUS = 'ending'";
			endFlowMap = queryTask(PO, BILL_WHERE);
			
			BILL_WHERE = " BIZ_DJBH = '" + F_DJBH + "' and BIZ_DATE = '" + F_KJQJ + "' and BIZ_GUID = '" + F_GUID + "' and FLOW_ID = 'PSHT_EDIT_FLOW' and "
                       + " RESR_STATUS = 'pending' and NODE_SRC = 'N3' and NODE_TAG = 'N4'";
			departmentConfrimeFlowMap = queryTask(PO, BILL_WHERE);
			
			CMSFlowPermission.checkFormStatus(model, rowset, dataset, nodeRowset, flowRowSet, nextFlowRowSet, user);
			
			if(flowRowSet != null && flowRowSet.getString("NODE_SRC", "").equals("N2") && flowRowSet.getString("NODE_TAG", "").equals("N3")) {
				for(int i = 0; i < dataset.getRowCount(); i++) {
					itemRowset = dataset.getRowSet(i);
					if(endFlowMap.get(itemRowset.getString("F_BMBH", "")) == null) {
						itemRowset.putString("FLOW_END", "0");
					} else {
						itemRowset.putString("FLOW_END", "1");
					}
					
					if(departmentConfrimeFlowMap.get(itemRowset.getString("F_BMBH", "")) == null) {
						itemRowset.putString("OP_TYPE", "1");
					} else {
						itemRowset.putString("OP_TYPE", "0");
					}
				}
			}
			
			if(flowRowSet != null && flowRowSet.getString("NODE_SRC", "").equals("N3") && flowRowSet.getString("NODE_TAG", "").equals("N4")) {
				for(int i = 0; i < dataset.getRowCount(); i++) {
					itemRowset = dataset.getRowSet(i);
					if(itemRowset.getString("F_BMBH", "").equals(user.getUSER_ORGID())) {
						itemRowset.putString("OP_RETAKE", "1");
						bRetake = true;
					} else {
						itemRowset.putString("OP_RETAKE", "0");						
					}
				}
			} else {
				for(int i = 0; i < dataset.getRowCount(); i++) {
					itemRowset = dataset.getRowSet(i);
					if(retakeMap.get(itemRowset.getString("F_BMBH", "")) == null) {
						itemRowset.putString("OP_RETAKE", "0");
					} else {
						model.addAttribute("FORM_RETAKE", "1");
						itemRowset.putString("OP_RETAKE", "1");
						bRetake = true;
					}
				}
			}
			
			
			//判断是否超期
			for(int i = 0; i < dataset.getRowCount(); i++) {
				endDate = "";
				itemRowset = dataset.getRowSet(i);
				jzrq = itemRowset.getDate("F_JZRQ", null);
				xgJzrq = itemRowset.getDate("XG_JZRQ", null);
				qrrq = itemRowset.getDate("F_QRRQ", null);
				
				date = (xgJzrq == null ? jzrq : xgJzrq);
				if(date != null) endDate = date.toString().replaceAll("-", "");
				
				if(qrrq == null) {
					date = (xgJzrq == null ? jzrq : xgJzrq);
					if(date != null) endDate = date.toString().replaceAll("-", "");
					curDate = DateUtil.date3String("yyyyMMdd");
					
					//如果没有确认的话，判断修改截止日期或者截止日期和当前日期的间隔天数，超过显示超期，未超过显示未确认，不能显示如期
					if(!endDate.equals("")) {
						if(curDate.compareTo(endDate) > 0) {
							itemRowset.putString("F_QRZT", "2");
						} else {
							itemRowset.putString("F_QRZT", "0");
						}
					}	
				} else {
					curDate = qrrq.toString().replaceAll("-", "");
					if(curDate.compareTo(endDate) <= 0) {
						itemRowset.putString("F_QRZT", "1");
					} else if(curDate.compareTo(endDate) > 0){
						itemRowset.putString("F_QRZT", "2");
					}
				}			
			}
			
			model.addAttribute("curDate", DateUtil.date3String(DateUtil.PATTERN_DATE));
			model.addAttribute("dictObject", rowset);
			model.addAttribute("dataset", dataset);
			model.addAttribute("nodeRowset", nodeRowset);
			model.addAttribute("flowRowSet", flowRowSet);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(bRetake || flowRowSet == null) {
			return "/cms/business/accreditationContractModifyApproval/form";
		}
		if(nodeRowset == null || nodeRowset.getString("NODE_ID", "N2").equals("N3") || nodeRowset.getString("NODE_ID", "N2").equals("N4") || (flowRowSet.getString("NODE_SRC", "N4").equals("N4") && flowRowSet.getString("NODE_TAG", "N2").equals("N2"))) {
			return "/cms/business/accreditationContractModifyApproval/form";
		} else if(nodeRowset == null || nodeRowset.getString("NODE_ID", "N2").equals("N2")) {
			return "/cms/business/accreditationContractApproval/form";
		} else {
			return "/cms/business/accreditationContractManagerApproval/form";
		}
	}	
	
	private Map<String, EFRowSet> queryTask(JParamObject PO, String BILL_WHERE) {
		EFDataSet                    flowDataSet =  EFDataSet.getInstance(new String[]{"TASK_TO_UNIT"});
		Map<String, EFRowSet>            flowMap = new HashMap<String, EFRowSet>();
		
		
		//检索有经理审批后部门退回的任务
		PO.SetValueByParamName("tableName", "FLOW_TASK_LIST");
		PO.SetValueByParamName("BILL_WHERE", BILL_WHERE);
		flowDataSet = FCTService.getFCTRows(PO);
		for(int i = 0; i < flowDataSet.getRowCount(); i++) {
			flowMap.put(flowDataSet.getRowSet(i).getString("TASK_TO_UNIT", ""), flowDataSet.getRowSet(i));
		}
		return flowMap;
	}
	
	/**
	 * 取回评审合同
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/accreditationContractApproval/rollback", method=RequestMethod.POST)
	public  ModelAndView accreditationContractApprovalRollback(@RequestBody Map dataMap, Model model) throws Exception {  
		EFRowSet              rowSet = EMPJsonUtil.convertMapToRowSet(dataMap);
		EFDataSet        itemDataSet = rowSet.getDataSet(PSHTMX.class.getName());
		EFRowSet              rowset = EFRowSet.getInstance();
		String              F_CHDATE = "";
		JParamObject              PO = JParamObject.Create();
		JParamObject          flowPO = JParamObject.Create();
		EFDataSet         flowNodeDS = null;
		EFRowSet          nodeRowset = EFRowSet.getInstance();
		SYSUser                 user = (SYSUser) session.getAttribute("contextUser");
		String            BILL_WHERE = " OP_ID = '" + rowSet.getString("OP_ID", "") + "'";

		PO.SetValueByParamName("tableName", "FLOW_TASK_LIST");
		PO.SetValueByParamName("BILL_WHERE", BILL_WHERE);
		EFRowSet          flowRowSet = FCTService.getFCTRow(PO);

		
		//获取流程节点
		flowPO.SetValueByParamName("TABLE_NAME", "FLOW_NODE_LIST");
		flowPO.SetValueByParamName("FLOW_ID", "PSHT_EDIT_FLOW");
		flowPO.SetValueByParamName("FLOW_BM", user.getUSER_ORGID());
		flowPO.SetValueByParamName("FLOW_USER", user.getUSER_ID());
		flowPO.SetValueByParamName("NODE_ID", flowRowSet.getString("NODE_TAG", ""));
		flowPO.SetValueByParamName("BILL_ORDER", " NODE_ID");
		
		flowNodeDS = FlowManagerService.loadFlowNode(flowPO);
		nodeRowset = flowNodeDS.getRowSet(0);

		if(nodeRowset == null) {
			return ajaxDoneError("提交失败！原因：<br>【" + user.getUSER_ID() + "-" + user.getUSER_NAME() + "】没有权限提交单据！");
		}

		itemDataSet.setTableName("PSHTMX");
		rowset.setDataMap(rowSet.getDataMap());
		rowset.remove(PSHTMX.class.getName());
		rowset.putString("F_DJZT", "2");
		rowset.putString(EFFormDataModel._FORMEDITSAVETYPE_, "" + EFFormDataModel._FORM_SAVE_HEAD_);
		
		PO.SetValueByParamName(SYS_MODEL.SERVICE_ID, "RollbackApprovalPSHTRToFlow");
		PO.SetValueByParamName(SYS_MODEL.MODEL_ID, "PSHTModel");
		
		PO.SetValueByParamName(FLOW_TASK_LIST._OP_ID, flowRowSet.getString("OP_ID", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._FLOW_ID, "PSHT_EDIT_FLOW");
		PO.SetValueByParamName(FLOW_TASK_LIST._OP_NODE, nodeRowset.getString("NODE_ID", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._OP_NODE_TYPE, nodeRowset.getString("NODE_TYPE", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._NODE_SRC, nodeRowset.getString("NODE_ID", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._NODE_SRC_NAME, nodeRowset.getString("NODE_NAME", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._OP_BMBH, user.getUSER_ORGID());
		PO.SetValueByParamName(FLOW_TASK_LIST._OP_USER, user.getUSER_ID());
		PO.SetValueByParamName(FLOW_TASK_LIST._TASK_TO_UNIT, user.getUSER_ORGID());
		PO.SetValueByParamName(FLOW_TASK_LIST._OP_USER_NAME, user.getUSER_NAME());
		PO.SetValueByParamName(FLOW_TASK_LIST._RESR_OUT_CAUSE, "rollback");
		PO.SetValueByParamName(FLOW_TASK_LIST._RESR_STATUS, "pending");
		PO.SetValueByParamName(FLOW_TASK_LIST._RESR_IN_CAUSE, "rollback");
		PO.SetValueByParamName(FLOW_TASK_LIST._OP_NOTE, dataMap.get("OP_NOTE").toString());
		PO.SetValueByParamName(FLOW_TASK_LIST._F_CHAR + "01", rowset.getString("F_KHBH", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._F_CHAR + "02", rowset.getString("F_KHMC", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._F_CHAR + "03", rowset.getString("F_XMBH", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._F_CHAR + "04", rowset.getString("F_XMMC", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._F_CHAR + "05", rowset.getString("F_BZ", ""));
		PO.SetValueByParamName(FLOW_TASK_LIST._F_CHAR + "06", rowset.getString("F_FSCS", ""));
		
		EFFormDataModel formDataModel = formModelResolver.saveForm("PSHTXX", rowset, PO);
		if(formDataModel.getFormSaveStatus() == EFFormDataModel._FORM_SAVE_ITEMS_ALL_) {
			return ajaxDoneError("单据提交失败！原因：<br>" + formDataModel.getFormSaveMessage());
		}
		rowset = formDataModel.getBillDataSet().getRowSet(0);
		F_CHDATE = rowset.getObject("F_CHDATE", "").toString();
		model.addAttribute("F_CHDATE", F_CHDATE);
		model.addAttribute("F_DJBH", rowset.getObject("F_DJBH", ""));
		model.addAttribute("OP_ID", PO.GetValueByParamName(FLOW_TASK_LIST._OP_ID, ""));
		return ajaxDoneSuccess("单据提交成功！"); 
	}
}
